import React from 'react'
import { Text, View, Image, TouchableOpacity, ImageBackground } from 'react-native'
import { API, WINDOW } from '../Services'
import ImagePicker from 'react-native-image-picker'
import ImagePicker_mult from 'react-native-image-crop-picker'
import underscore from 'underscore'
import Video from 'react-native-video'
import { Metrics } from '../Themes'

export default class AddPhotoView extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      type:0,
      selectedPhotos: [],
      maxNum:this.props.maxNum || 9,
    }
  }

  deletePhoto(index) {
    let array = this.state.selectedPhotos
    array.splice(index, 1)
    this.setState({
      selectedPhotos: array,
    })
  }

  rendPhotos(element, index) {
    if (element.mime.indexOf('video') != -1) {
      return (
        <View style={{ marginLeft: 10, marginBottom: 10}} key={index}>
          <View style={{ justifyContent: 'center', alignItems: 'center'}}>
            <Video source={{ uri: element.path }}
              style={{ width: 112, height: 112 }}
              paused={true}
              resizeMode='cover'
            />
            <Image source={require('../Images/icon_bf.png')} style={{ position: 'absolute' }} />
          </View>
          <TouchableOpacity onPress={() => this.deletePhoto(index)} style={{ position: 'absolute', right: -10, top: -10, padding: 8 }}>
            <Image source={require('../Images/close.png')} style={{}} />
          </TouchableOpacity>
        </View>
      )
    } else {
      return (
        <ImageBackground style={{ width: (Metrics.screenWidth-48)/3 , height: (Metrics.screenWidth-48)/3, marginLeft: 12, marginBottom: 10 }} source={{ uri: element.path }} key={index} >
          <TouchableOpacity onPress={() => this.deletePhoto(index)} style={{ position: 'absolute', right: -10, top: -10, padding: 8 }}>
            <Image source={require('../Images/close.png')} style={{}} />
          </TouchableOpacity>
        </ImageBackground>
      )
    }  
  }

  _selectPhoto() {
    let BUTTONS = ['拍摄', '从手机相册选择', '取消']
    WINDOW.showActionSheet(
      {
        title: '选择',
        options: BUTTONS,
        cancelButtonIndex: BUTTONS.length - 1,
      },
      buttonIndex => {
        if (buttonIndex === BUTTONS.length - 1) {
          return
        } else if (buttonIndex === 0) {
          this._selectFromCamera()
        } else if (buttonIndex === 1) {
          this._selectFromPhoto()

        }
      },
    )
  }  
  
  _selectFromPhoto() {
    let mediaType
    if (this.props.onlyImage) {
      mediaType = 'photo'
    } else {
      mediaType = 'any'
    }
    ImagePicker_mult.openPicker({
      mediaType: 'photo',
      multiple: true,  
      maxFiles: 9,
      compressImageMaxWidth: 2100,
      compressImageMaxHeight: 2100,
      compressImageQuality: 0.4,
    }).then(images => {
      console.log(images);
      let selectedPhotos = this.state.selectedPhotos.concat(images)
      selectedPhotos = underscore.first(selectedPhotos, this.state.maxNum)
      this.setState({
        selectedPhotos
      })
    });
  }

  _selectFromCamera() {
    ImagePicker_mult.openCamera({
      compressImageQuality: 0.3,
    }).then(image => {
      console.log(image);
      let selectedPhotos = this.state.selectedPhotos.concat(image)
      selectedPhotos = underscore.first(selectedPhotos, this.state.maxNum)
      this.setState({
        selectedPhotos
      })
    });
  }


  // _selectPhoto() {
  //   if (this.state.selectedPhotos.length == this.state.maxNum) {
  //     return WINDOW.showToast('超过最大限制！')
  //   }
  //   var options = {
  //     title: this.state.type == 0 ? '选择图片' : '选择视频', // specify null or empty string to remove the title
  //     cancelButtonTitle: '取消',
  //     takePhotoButtonTitle: this.state.type == 0 ? '拍照' : '拍摄', // specify null or empty string to remove this button
  //     chooseFromLibraryButtonTitle: '从手机相册选择', // specify null or empty string to remove this button
  //     cameraType: 'back', // 'front' or 'back'
  //     mediaType: this.state.type == 0 ? 'photo' : 'video', // 'photo' or 'video'
  //     quality: 0.5, // 0 to 1, photos only
  //     videoQuality: 'low',
  //     maxWidth: 1000,
  //     maxHeight: 2000,
  //     allowsEditing: false, // Built in functionality to resize/reposition the image after selection
  //     noData: true, // photos only - disables the base64 `data` field from being generated (greatly improves performance on large photos)
  //   }
  //   ImagePicker.showImagePicker(options, (response) => {
  //     console.log('Response = ', response)
  //     if (response.didCancel) {
  //       console.log('User cancelled image picker')
  //     }
  //     else if (response.error) {
  //       console.log('ImagePickerManager Error: ', response.error)
  //     } else {
  //       this.setState({
  //         selectedPhotos: this.state.selectedPhotos.concat(response)
  //       })
  //     }
  //   })
  // }



  _doUploadMeia = () => {
    if (!this.state.selectedPhotos.length) {
      return WINDOW.showToast('请上传图片或视频！')
    }
    if (this.state.selectedPhotos.length > 1) {
      let array = this.state.selectedPhotos
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element.mime.indexOf('video') != -1) {
          return WINDOW.showToast('只能上传一个视频！')
        }
      }
    }
    this._uploadImage()
  }

  //上传图片
  _uploadImage = () => {
    let imag = this.state.selectedPhotos
    let key = WINDOW.showToastLoad()
    API.uploadImage(imag).then((response) => {
      WINDOW.hideToast(key)
      const { ok, data } = response
      let file = data?.data
      if (ok && data.code === 1) {
        let imagePaths
        if (underscore.isArray(file)) {
          let pathArray = file.map((element) => element.filepath)
          imagePaths = pathArray.join(',')
          this.props.selectImageCallback(imagePaths)
        } else {
          this.props.selectImageCallback(file.filepath)
        }
      } else {
        WINDOW.showToastError(data.msg || '请求失败！')
      }
    })
  }

  render() {
    return (
      <View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap' }}>
        {this.state.selectedPhotos.map(this.rendPhotos.bind(this))}
        <TouchableOpacity onPress={this._selectPhoto.bind(this)}>
          <Image source={require('../Images/fabu_icon_sahngchuan_nor.png')} style={{marginLeft: 10, marginBottom: 10 }} />
        </TouchableOpacity>
        <Text style={{ color: 'gray', fontSize: 18, alignSelf: 'flex-end', marginLeft: 15, marginBottom: 10 }}>
          {this.state.selectedPhotos.length}/{this.state.maxNum}
        </Text>
      </View>
    )
  }
}
